#include <iostream>
#include <cerrno>
#include <cstring>
#include <string>
#include <unistd.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Pthread.hpp"
#include "InetAddr.hpp"
using namespace std;
class ThreadData
{
public:
    ThreadData(int sock, struct sockaddr_in &server) : _sockfd(sock), _serveraddr(server)
    {
    }
    ~ThreadData()
    {
    }

public:
    int _sockfd;
    InetAddr _serveraddr;
};
void RecverRoutine(ThreadData &td)
{
    char buffer[4096];
    while (true)
    {
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t n = recvfrom(td._sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len); // 一般建议都是要填的.
        if (n > 0)
        {
            buffer[n] = 0;
            std::cerr << buffer << std::endl; // 方便一会查看效果
        }
        else
            break;
    }
}
void SenderRoutine(ThreadData &td)
{
    while (true)
    {
        string massage;
        cout << "please enter#";
        getline(cin, massage);
        auto server = td._serveraddr.Getaddr();
        ssize_t n = sendto(td._sockfd, massage.c_str(), sizeof(massage), 0, (struct sockaddr *)&server, sizeof(server));
        if (n <= 0)
            cout << "send error" << endl;
    }
}
void useage(std::string &process)
{
    std::cout << "usage" << process << " server_ip server_port" << std::endl;
}
int main(int argc, char *argv[])
{
    std::string use = argv[0];
    if (argc != 3)
    {
        useage(use);
        return 1;
    }
    std::string serverip = argv[1];
    uint16_t port = atoi(argv[2]);
    // 1.创建socket
    int _sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (_sock < 0)
    {
        std::cerr << "socket error: " << strerror(errno) << std::endl;
        return 2;
    }
    std::cout << "create socket success: " << _sock << std::endl;
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    ThreadData td(_sock, server);
    Thread<ThreadData> recver("reccer", RecverRoutine, td);
    Thread<ThreadData> sender("sender", SenderRoutine, td);
    recver.Start();
    sender.Start();

    recver.Join();
    sender.Join();
    close(_sock);
    return 0;
}